---
title: "A Revolt of the Distrustful? Political Trust, Political Protest and the Democratic Deficit"
author: "Edgar Grande and Daniel Saldivia Gonzatti"
date: \today
output: 
  html_document:
    code_folding: hide
    toc: true
    toc_float:
      collapsed: false
      smooth_scroll: false   
---

```{r setup, include=FALSE}
library(pastecs)
library(dplyr)
library(sjPlot)
library(haven)
library(stargazer)
library(devtools)
library(kableExtra)
library(ggplot2)
library(interactions)
library(tidyverse)
library(jtools)
library(ggstance)
library(glmnet)
library(patchwork)
library(ggridges)
library(arm)
library(list)
library(psych)
library(mosaic)
library(stats)
library(summarytools)
library(ggeffects)
library(CGPfunctions)
library(ggarchery)
library(ggpubr)
library(marginaleffects)

# Set up
knitr::opts_chunk$set(fig.width=6, fig.height=4)
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
```


# Description

This markdown file reproduces the analysis and results of the paper by Grande and Saldivia Gonzatti (2025).

Link: https://doi.org/10.1080/13501763.2024.2447457

Cite as: Grande, Edgar and Saldivia Gonzatti, Daniel (2025). A Revolt of the Distrustful? Political Trust, Political Protest and the Democratic Deficit;
in: Journal of European Public Policy, Online first. DOI: https://doi.org/10.1080/13501763.2024.2447457.

1. `main_survey_data_revolt.RData`: Survey data from February 2022 (Covid-19 crisis) and December 2022/January 2023 (Ukraine crisis).
2. `time_series_trust.RData`: Time series data on trust in the German government and parliament from June 2020 to December 2023.
3. `Eurobarometer` and `ESS` data must be downloaded directly from the source (see indications below).


The variables in the dataset from `main_survey_data_revolt.RData` are described in more detail in the Supplementary Material of the article. There, we include the wording of the survey items as well as the scales. In the variable names, "cor" refers to Covid-19 protests and "ener" to energy protests. The `time_series_trust.RData` data set only includes the trust_government and trust_parliament variables with the wording and scales as described in the Supplementary Materials of the article.

# Original survey data

Load data:

```{r}
load("data/main_survey_data_revolt.RData")
load("data/time_series_trust.RData")

```



## Figure 2: Trust in the German government and across institutions during two crises, 2022 and 2023

```{r warning=FALSE, echo = TRUE, message = FALSE, results = TRUE, fig.width=12,fig.height=8}


wave_1_trust.gov_plot <- ggplot(data %>% dplyr::filter(wave==1), aes(trust_government)) + 
geom_bar(aes(y = after_stat((..count..)/sum(..count..))), stat= "count") +
geom_text(aes(label = after_stat(scales::percent((..count..)/sum(..count..),
                                                 accuracy = 1)),
            y= after_stat(((..count..)/sum(..count..)))), stat="count",
        vjust = -.25) + ylab("Respondents (%)") + xlab("COVID-19 crisis; February 2022") + theme_minimal()

wave_2_trust.gov_plot <- ggplot(data %>% dplyr::filter(wave==3), aes(trust_government)) + 
geom_bar(aes(y = after_stat((..count..)/sum(..count..))), stat= "count") +
geom_text(aes(label = after_stat(scales::percent((..count..)/sum(..count..),
                                                 accuracy = 1)),
            y= after_stat(((..count..)/sum(..count..)))), stat="count",
        vjust = -.25) + ylab("") + xlab("Ukraine crisis; December 2022/January 2023") + theme_minimal()


aggr_distrust.values <- left_join(
  data %>% dplyr::filter(!gender==3) %>% 
    group_by(wave) %>% summarise(
      across(c(trust_government, trust_parliament,
               trust_reg.government, trust_local.government,
               trust_eu, trust_parties,
               trust_judges, trust_police,
               trust_media, truist_medicine,
               trust_scietific.committees, trust_science), ~ mean(.))
    ) %>% 
    pivot_longer(!wave) %>% 
    pivot_wider(names_from = wave, values_from = value) ,
  
  data %>% dplyr::filter(!gender==3) %>% 
    group_by(wave) %>% summarise(
      across(c(trust_government, trust_parliament,
               trust_reg.government, trust_local.government,
               trust_eu, trust_parties,
               trust_judges, trust_police,
               trust_media, truist_medicine,
               trust_scietific.committees, trust_science), ~ sum(.==0, na.rm = TRUE)),
      count = n()
    ) %>% 
  pivot_longer(!c(wave, count)) %>% 
  mutate(value = if_else(value==0,NA,value)) %>%
  mutate(share = value/count*100) %>% dplyr::select(-count) %>% 
  pivot_wider(names_from = wave, values_from = c(value, share)) %>% 
  dplyr::select(name, value_1, share_1, value_3, share_3) )


distrust <- aggr_distrust.values %>% 
  dplyr::filter(!name %in% c("truist_medicine", "trust_science",
                             "trust_scietific.committees")) %>% 
  dplyr::select(c(name, `1`, share_1)) %>% 
  dplyr::rename(mean = 2, share = 3) %>% mutate(wave = " 1") %>% 
  bind_rows(
    aggr_distrust.values %>% dplyr::filter(!name %in% c("truist_medicine", "trust_science",
                                                        "trust_scietific.committees")) %>% 
      dplyr::select(c(name, `3`, share_3)) %>% 
      dplyr::rename(mean = 2, share = 3) %>% mutate(wave = "2")) %>% 
  mutate(var_full = paste0(name, "\n", wave)) %>% 
  mutate(share = round(share, 1)) %>% 
  mutate(name = case_when(name=="trust_government" ~ "Federal\nGovernment",
                          name=="trust_eu" ~ "EU",
                          name=="trust_judges" ~ "Judiciary/courts",
                          name=="trust_local.government" ~ "Local gov.\n(Gemeinde/Stadt)",
                          name=="trust_reg.government" ~ "Regional\ngov. (Land)",
                          name=="trust_parliament" ~ "Bundestag",
                          name=="trust_parties" ~ "Political parties",
                          name=="trust_media" ~ "Media",
                          name=="trust_police" ~ "Police",
                          TRUE ~ name)) %>% 
  dplyr::filter(! (name %in% c("Media","Political parties"))) %>% 
  mutate(name = factor(name, levels =c("Federal\nGovernment",
                                       "Bundestag","EU",
                                       "Regional\ngov. (Land)",
                                       "Local gov.\n(Gemeinde/Stadt)",
                                       "Judiciary/courts","Police"))) %>%
  ggplot(aes(x=wave, y=share, fill = wave)) + 
  geom_bar(position=position_dodge(), stat="identity", 
           colour='black', width = 0.85) + 
  scale_fill_manual(values=c('lightgrey','white')) +
  xlab("Wave") +  theme_minimal() + ylab("Distrustful group share (% = 0)") +
  ggtitle("(B) Distrust across institutions") + 
  geom_text(aes(label=share), vjust=3) + guides(fill = FALSE)  +
  facet_grid(~name) 

((wave_1_trust.gov_plot + ggtitle("(A) Trust in government")) | wave_2_trust.gov_plot) / distrust


ggsave(filename="visualizations/figure_2_manuscript.jpeg",
       plot=last_plot(), device="png", units="cm", width=25, height=20, dpi=300)

rm(distrust, wave_1_trust.gov_plot, wave_2_trust.gov_plot)

```

## Table 5: Political trust across institutions and across crises (SuppMat)

```{r warning=FALSE, echo = T, message = FALSE, results = TRUE, fig.width=12,fig.height=8}


aggr_distrust.values %>%  
  dplyr::select(name,`1`, value_1, share_1, `3`, value_3, share_3) %>% 
  dplyr::rename(Institution = name, Mean_Covid_19 = `1`, N_Covid_19 = value_1,
                Share_Covid_19 = share_1, Mean_Ukraine = `3`,
                N_Ukraine = value_3, Share_Ukraine = share_3) %>%
  kable(caption = "Table 5: Political trust across institutions and across crises")

rm(aggr_distrust.values)
```



## Figure 6: Trust in the German national parliament during two crises, 2022 and 2023

```{r echo = T, warning = FALSE, results = T, fig.width=9,fig.height=3.5, eval = TRUE}
wave_1_trust_plot <- ggplot(data %>% dplyr::filter(wave==1), aes(trust_parliament)) + 
geom_bar(aes(y = after_stat((..count..)/sum(..count..))), stat= "count") +
geom_text(aes(label = after_stat(scales::percent((..count..)/sum(..count..),
                                                 accuracy = 1)),
            y= after_stat(((..count..)/sum(..count..)))), stat="count",
        vjust = -.25) + ylab("Respondents (%)") + xlab("COVID-19 crisis; February 2022") + theme_minimal() +
  ylim(0,0.22) +
  scale_x_continuous(
                    breaks=c(0,3,5,7,10))

wave_2_trust_plot <- ggplot(data %>% dplyr::filter(wave==3), aes(trust_parliament)) + 
geom_bar(aes(y = after_stat((..count..)/sum(..count..))), stat= "count") +
geom_text(aes(label = after_stat(scales::percent((..count..)/sum(..count..),
                                                 accuracy = 1)),
            y= after_stat(((..count..)/sum(..count..)))), stat="count",
        vjust = -.25) + ylab("") + xlab("Ukraine crisis; December 2022/January 2023") + theme_minimal()  +
  ylim(0,0.22) +
  scale_x_continuous(
                    breaks=c(0,3,5,7,10))


wave_1_trust_plot | wave_2_trust_plot 


rm(wave_1_trust_plot, wave_2_trust_plot )

```



## Figure 18: Distribution of political deprivation across the two crises, COVID-19 crisis and Ukraine crisis


```{r echo = T, warning = FALSE, results = T, fig.width=9,fig.height=3.5, eval = TRUE}

wave_1_depri_plot <- ggplot(data %>% dplyr::filter(wave==1), aes(pol_deprivation)) + 
geom_bar(aes(y = after_stat((..count..)/sum(..count..))), stat= "count") +
   scale_x_continuous(breaks = c(1:7)) +
geom_text(aes(label = after_stat(scales::percent((..count..)/sum(..count..),
                                                 accuracy = 1)),
            y= after_stat(((..count..)/sum(..count..)))), stat="count",
        vjust = -.25) + ylab("Respondents (%)") + xlab("COVID-19 crisis; February 2022") + theme_minimal() +
  ylim(0,0.25)

wave_2_depri_plot <- ggplot(data %>% dplyr::filter(wave==3), aes(pol_deprivation)) + 
geom_bar(aes(y = after_stat((..count..)/sum(..count..))), stat= "count") +
   scale_x_continuous(breaks = c(1:7)) +
geom_text(aes(label = after_stat(scales::percent((..count..)/sum(..count..),
                                                 accuracy = 1)),
            y= after_stat(((..count..)/sum(..count..)))), stat="count",
        vjust = -.25) + ylab("") + xlab("Ukraine crisis; December 2022/January 2023") + theme_minimal() +
  ylim(0,0.25)


wave_1_depri_plot | wave_2_depri_plot 

rm(wave_1_depri_plot, wave_2_depri_plot )

```

## Figure 19: Distribution of satisfaction with democracy across the two crises, COVID-19 crisis and Ukraine crisis

```{r echo = T, warning = FALSE, results = T, fig.width=9,fig.height=3.5, eval = TRUE}

wave_1_satis <- ggplot(data %>% dplyr::filter(wave==1), aes(satisfaction_german.democracy)) + 
geom_bar(aes(y = after_stat((..count..)/sum(..count..))), stat= "count") + 
  scale_x_continuous(breaks = c(1:7)) +
geom_text(aes(label = after_stat(scales::percent((..count..)/sum(..count..),
                                                 accuracy = 1)),
            y= after_stat(((..count..)/sum(..count..)))), stat="count",
        vjust = -.25) + ylab("Respondents (%)") + xlab("COVID-19 crisis; February 2022") + theme_minimal() +
  ylim(0,0.28)

wave_2_satis <- ggplot(data %>% dplyr::filter(wave==3), aes(satisfaction_german.democracy)) + 
geom_bar(aes(y = after_stat((..count..)/sum(..count..))), stat= "count") +
  scale_x_continuous(breaks = c(1:7)) +
geom_text(aes(label = after_stat(scales::percent((..count..)/sum(..count..),
                                                 accuracy = 1)),
            y= after_stat(((..count..)/sum(..count..)))), stat="count",
        vjust = -.25) + ylab("") + xlab("Ukraine crisis; December 2022/January 2023") + theme_minimal() +
  ylim(0,0.28)


wave_1_satis | wave_2_satis 
rm(wave_1_satis, wave_2_satis)

```
 
 
## Figure 20: Distribution of pro-direct democracy attitudes across the two crises, COVID-19 crisis and Ukraine crisis

```{r echo = T, warning = FALSE, results = T, fig.width=9,fig.height=3.5, eval = TRUE}

wave_1_dd <- ggplot(data %>% dplyr::filter(wave==1), aes(pro_referenda_binding)) + 
geom_bar(aes(y = after_stat((..count..)/sum(..count..))), stat= "count") + 
  scale_x_continuous(breaks = c(1:7)) +
geom_text(aes(label = after_stat(scales::percent((..count..)/sum(..count..),
                                                 accuracy = 1)),
            y= after_stat(((..count..)/sum(..count..)))), stat="count",
        vjust = -.25) + ylab("Respondents (%)") + xlab("COVID-19 crisis; February 2022") + theme_minimal() +
  ylim(0,0.28)

wave_2_dd <- ggplot(data %>% dplyr::filter(wave==3), aes(pro_referenda_binding)) + 
geom_bar(aes(y = after_stat((..count..)/sum(..count..))), stat= "count") + 
  scale_x_continuous(breaks = c(1:7)) +
geom_text(aes(label = after_stat(scales::percent((..count..)/sum(..count..),
                                                 accuracy = 1)),
            y= after_stat(((..count..)/sum(..count..)))), stat="count",
        vjust = -.25) + ylab("") + xlab("Ukraine crisis; December 2022/January 2023") + theme_minimal() +
  ylim(0,0.28)


wave_1_dd | wave_2_dd 
rm(wave_1_dd, wave_2_dd)

```


## Re-coding and re-categorisation

In the following code batch I create new variables related to the understanding and willingness to participate in COVID-19 and energy protests, generating new binary indicators. Additionally, I re-level the education and party ideology variables. Finally, I re-code the trust in government variable into three categories: no trust, low trust, and high trust. These adaptions serve to conduct the following analyses.


```{r echo = T}
# Re-coding

## Make binary DV for mobilisation variables
data$cor.protest_understanding.bin <- ifelse(data$cor.protest_understanding.lab == "3. Sehr viel/viel", 1, 0)
data$ener.protest_understanding.bin <- ifelse(data$ener.protest_understanding.lab == "3. Sehr viel/viel", 1, 0)

data$cor.protest_willingness.bin <- ifelse(data$cor.protest_willingness.lab == "3. Sicher/Wahrscheinlich", 1, 0)
data$ener.protest_willingness.bin <- ifelse(data$ener.protest_willingness.lab == "3. Sicher/Wahrscheinlich", 1, 0)


## Re-level and base category: education and party ideology
data$educ_category <- relevel(as.factor(data$educ_category), "niedrig")

data <- data %>% mutate(party_ideology.spd = 
                          factor(party_ideology, 
                                 levels = c("SPD","nicht repräsentiert", "weiß nicht","AfD",
                                            "Die Linke","FDP","Union",
                                            "Bündnis 90/Die Grünen")))


data <- data %>% mutate(trust_government_bins = case_when(trust_government==0 ~ "No trust",
                                                       trust_government>=1 & trust_government<=5  ~ "Low trust",
                                                       trust_government >=6 ~ "High trust"))

data <- data %>% mutate(trust_government_bins.fc = factor(trust_government_bins, 
                                                          levels = c("No trust", "Low trust", "High trust")))

```




## Figure 17: Distribution of ideological positions among political trust groups, COVID-19 crisis (February 2022, upper) and Ukraine crisis (December 2022/January 2023, bottom)


```{r, echo=T, warning=F, message=F, fig.width=12.5, fig.height=4.5}
no_trust.left_right <- ggplot(data %>% filter(trust_government_bins == "No trust" & wave == 1), aes(x = left_right)) + 
  geom_histogram(aes(y = after_stat(count / sum(count))), bins = 11) + theme_bw() +
  scale_y_continuous(labels = scales::percent) + ylab("Individuals %") + xlab("") +
  geom_text(aes(label = after_stat(scales::percent(round((..count..)/sum(..count..),2))),
            y= after_stat(((..count..)/sum(..count..)))+0.05), stat="count",
        vjust = -.25) +
  ggtitle("No trust") +  ylim(0,0.6)

low_trust.left_right <- ggplot(data %>% filter(trust_government_bins == "Low trust" & wave == 1), aes(x = left_right)) + 
  geom_histogram(aes(y = after_stat(count / sum(count))), bins = 11) + theme_bw() +
  scale_y_continuous(labels = scales::percent) + ylab("") + xlab("Left-Right") +
  geom_text(aes(label = after_stat(scales::percent(round((..count..)/sum(..count..),2))),
            y= after_stat(((..count..)/sum(..count..)))+0.05), stat="count",
        vjust = -.25) +
  ggtitle("Low trust") + ylim(0,0.6)

high_trust.left_right <- ggplot(data %>% filter(trust_government_bins == "High trust" & wave == 1), aes(x = left_right)) + 
  geom_histogram(aes(y = after_stat(count / sum(count))), bins = 11) + theme_bw() +
  scale_y_continuous(labels = scales::percent) + ylab("") + xlab("") +
  geom_text(aes(label = after_stat(scales::percent(round((..count..)/sum(..count..),2))),
            y= after_stat(((..count..)/sum(..count..)))+0.05), stat="count",
        vjust = -.25) +
  ggtitle("High trust") + ylim(0,0.6)


no_trust.left_right2 <- ggplot(data %>% filter(trust_government_bins == "No trust" & wave == 3), aes(x = left_right)) + 
  geom_histogram(aes(y = after_stat(count / sum(count))), bins = 11) + theme_bw() +
  scale_y_continuous(labels = scales::percent) + ylab("Individuals %") + xlab("") +
  geom_text(aes(label = after_stat(scales::percent(round((..count..)/sum(..count..),2))),
            y= after_stat(((..count..)/sum(..count..)))+0.05), stat="count",
        vjust = -.25) +
  ggtitle("No trust") +  ylim(0,0.6)

low_trust.left_right2 <- ggplot(data %>% filter(trust_government_bins == "Low trust" & wave == 3), aes(x = left_right)) + 
  geom_histogram(aes(y = after_stat(count / sum(count))), bins = 11) + theme_bw() +
  scale_y_continuous(labels = scales::percent) + ylab("") + xlab("Left-Right") +
  geom_text(aes(label = after_stat(scales::percent(round((..count..)/sum(..count..),2))),
            y= after_stat(((..count..)/sum(..count..)))+0.05), stat="count",
        vjust = -.25) +
  ggtitle("Low trust") + ylim(0,0.6)

high_trust.left_right2 <- ggplot(data %>% filter(trust_government_bins == "High trust" & wave == 3), aes(x = left_right)) + 
  geom_histogram(aes(y = after_stat(count / sum(count))), bins = 11) + theme_bw() +
  scale_y_continuous(labels = scales::percent) + ylab("") + xlab("") +
  geom_text(aes(label = after_stat(scales::percent(round((..count..)/sum(..count..),2))),
            y= after_stat(((..count..)/sum(..count..)))+0.05), stat="count",
        vjust = -.25) +
  ggtitle("High trust") + ylim(0,0.6)

(no_trust.left_right | low_trust.left_right | high_trust.left_right) / (no_trust.left_right2 | low_trust.left_right2 | high_trust.left_right2)
rm(no_trust.left_right, low_trust.left_right, high_trust.left_right, no_trust.left_right2, low_trust.left_right2, high_trust.left_right2)

```


## Table 12: Descriptive statistics of ideological groups across trust groups


```{r message = FALSE}
# Right

right_dist <- data %>% group_by(trust_government_bins, wave_chr, left_right = left_right>=9) %>%
  summarise(count = n()) %>% group_by(trust_government_bins, wave_chr) %>% 
  mutate(share = count/sum(count)) %>% dplyr::filter(left_right==TRUE) %>% 
  mutate(left_right = "Right")

# Center

center_dist <- data %>% group_by(trust_government_bins, wave_chr, left_right = left_right>=4 & left_right<=8) %>%
  summarise(count = n()) %>% group_by(trust_government_bins, wave_chr) %>% 
  mutate(share = count/sum(count)) %>% dplyr::filter(left_right==TRUE) %>% 
  mutate(left_right = "Center") 

# Left
left_dist <- data %>% group_by(trust_government_bins, wave_chr, left_right = left_right<=3) %>%
  summarise(count = n()) %>% group_by(trust_government_bins, wave_chr) %>% 
  mutate(share = count/sum(count)) %>%  dplyr::filter(left_right==TRUE) %>% 
  mutate(left_right = "Left") 

ideo_dists <- bind_rows(left_dist, center_dist, right_dist) %>% 
  arrange(wave_chr, trust_government_bins)

ideo_dists %>% 
  dplyr::rename("Political trust group" = 1, "Crisis/survey wave" = 2,
                Ideology = 3, N = count, "Respondents share" = share) %>% 
  kable(caption = "Table 12: Descriptive statistics of ideological groups across trust groups")

rm(ideo_dists, left_dist, center_dist, right_dist)

```


## Re-coding and re-categorisation II

The following code batch adapts variables such as gender and left-right; filters out NAs and drops individuals who identify as diverse; and creates new variables such as the square of age and left-right, and the absolute value of the difference between the respondent's left-right position and the center of the scale (6) (extremism). Additionally, I split the data into two datasets, one for the first wave (COVID-19 crisis) and one for the second wave (Ukraine crisis); this split makes the following analyses easier to code. Finally, I re-code the variables related to the support for democracy in Germany, which are coded as 99 ('not important at all' = 0).


```{r, echo=T}

# Re-coding
data <- data %>% dplyr::mutate(gender = as.numeric(gender)) %>%
  dplyr::filter(!gender==3) # Diverse identified respondents
data <- data %>% dplyr::filter(!is.na(left_right))
data <- data %>% mutate(age_2 = age*age, left_right_2 = left_right*left_right)
data <- data %>% mutate(pro_referenda_binding = as.numeric(pro_referenda_binding))
data <- data %>% mutate(extremisms_lr = abs(left_right-6))

# Separate the datasets by the first (Covid-19 crisis) and  second (Ukraine crisis) waves
data.w1 <- data %>% dplyr::filter(wave==1)
data.w2 <- data %>% dplyr::filter(wave==3)


# The following only applies to the second wave
data <- data %>% 
  mutate_at(c("democracygen_courtequality","democracygen_minortyrights",
              "democracygen_mediacritique"), ~ if_else(.==99,0,.)) %>% 
  mutate_at(c("democracygen_fairelections","democracygen_punishincumbent",
              "democracygen_partydifference"), ~ if_else(.==99,0,.)) %>%
  mutate_at(c("democracyger_courtequality","democracyger_minortyrights",
              "democracyger_mediacritique"), ~ if_else(.==99,0,.)) %>%
  mutate_at(c("democracyger_fairelections","democracyger_punishincumbent",
              "democracyger_partydifference"), ~ if_else(.==99,0,.))


data_select <- data %>%
  dplyr::select(trust_government, trust_parliament, cor.protest_understanding,
                cor.protest_willingness, energyprotest_understanding,
                energyprotest_propensity_participation, gender,
                age, educ_category, current_econ.situation, children.dummy,
                east_d, left_right, pro_migration_limit,
                pro_homosexual_lifestyle, anti_state_intervention.economy, 
                party_ideology.spd, pol_deprivation, 
                satisfaction_german.democracy, pro_referenda_binding,
                democracygen_courtequality, democracygen_minortyrights,
                democracygen_mediacritique, democracygen_fairelections, 
                democracygen_punishincumbent, democracygen_partydifference,
                democracyger_courtequality, democracyger_minortyrights,
                democracyger_mediacritique, democracyger_fairelections,
                democracyger_punishincumbent, democracyger_partydifference
  )

```


## Table 4: Dataset distributions

```{r}
print(dfSummary(data_select, 
                varnumbers   = FALSE, 
                valid.col    = FALSE, 
                graph.magnif = 0.76),
      method = 'render')

rm(data_select)
```


## Figure 12: Distribution of sympathy with the protest, COVID-19 crisis (February 2022) and Ukraine crisis (December 2022/January 2023)


```{r}

data <- data %>% mutate(cor_sympa_english =
                          case_when(cor.protest_understanding.lab=="1. Gar kein" ~ "1. None",
                                    cor.protest_understanding.lab=="2. Etwas" ~ "2. Some",
                                    cor.protest_understanding.lab=="3. Sehr viel/viel" ~ "3. A lot/very much"),
                        ener_sympa_english = 
                          case_when(ener.protest_understanding.lab=="1. Gar kein" ~ "1. None",
                                    ener.protest_understanding.lab=="2. Etwas" ~ "2. Some",
                                    ener.protest_understanding.lab=="3. Sehr viel/viel" ~ "3. A lot/very much"))

cor_protest_sym <- ggplot(data %>% dplyr::filter(wave==1), aes(cor_sympa_english)) + 
geom_bar(aes(y = after_stat((..count..)/sum(..count..))), stat= "count") + 
geom_text(aes(label = after_stat(scales::percent((..count..)/sum(..count..),
                                                 accuracy = 1)),
            y= after_stat(((..count..)/sum(..count..)))), stat="count",
        vjust = -.25) + ylab("Respondents (%)") + xlab("COVID-19 crisis; February 2022") + theme_minimal() +
  ylim(0,0.73)

ener_protest_sym <- ggplot(data %>% dplyr::filter(wave==3), aes(ener_sympa_english)) + 
geom_bar(aes(y = after_stat((..count..)/sum(..count..))), stat= "count") + 
geom_text(aes(label = after_stat(scales::percent((..count..)/sum(..count..),
                                                 accuracy = 1)),
            y= after_stat(((..count..)/sum(..count..)))), stat="count",
        vjust = -.25) + ylab("") + xlab("Ukraine crisis; December 2022/January 2023") + theme_minimal() +
  ylim(0,0.73)


cor_protest_sym | ener_protest_sym 

rm(cor_protest_sym, ener_protest_sym)

```

## Table 6: Sympathy with the protest among trust groups


```{r}

cor_sympathy_some <- data %>% dplyr::filter(wave==1) %>%
  group_by(trust_government_bins) %>% 
  summarise(count = n(),
            sympathy = sum(cor_sympa_english=="3. A lot/very much")) %>% 
  mutate(share = sympathy/count*100, 
         wave = "COVID-19 crisis")


ener_sympathy_some <- data %>% dplyr::filter(wave==3) %>%
  group_by(trust_government_bins) %>% 
  summarise(count = n(),
            sympathy = sum(ener_sympa_english=="3. A lot/very much")) %>% 
  mutate(share = sympathy/count*100, 
         wave = "Ukraine crisis")

bind_rows(cor_sympathy_some, ener_sympathy_some) %>%
  dplyr::relocate(wave) %>% 
  kable()

rm(cor_sympathy_some, ener_sympathy_some)

```


## Figure 13: Distribution of willingness to protest, COVID-19 crisis (February 2022) and Ukraine crisis (December 2022/January 2023)

```{r fig.width=9, fig.height=3.5, eval = TRUE}

data <- data %>% mutate(cor_will_english =
                          case_when(cor.protest_willingness.lab=="1. Sicher nicht" ~ "1. Not at all",
                                    cor.protest_willingness.lab=="2. Eher nicht" ~ "2. Some",
                                    cor.protest_willingness.lab=="3. Sicher/Wahrscheinlich" ~ "3. (Very) Likely"),
                        ener_will_english = 
                          case_when(ener.protest_willingness.lab =="1. Sicher nicht" ~ "1. None",
                                    ener.protest_willingness.lab=="2. Eher nicht" ~ "2. Some",
                                    ener.protest_willingness.lab=="3. Sicher/Wahrscheinlich" ~ "3. (Very) Likely"))

cor_protest_will <- ggplot(data %>% dplyr::filter(wave==1), aes(cor_will_english)) + 
geom_bar(aes(y = after_stat((..count..)/sum(..count..))), stat= "count") + 
geom_text(aes(label = after_stat(scales::percent((..count..)/sum(..count..),
                                                 accuracy = 1)),
            y= after_stat(((..count..)/sum(..count..)))), stat="count",
        vjust = -.25) + ylab("Respondents (%)") + xlab("COVID-19 crisis; February 2022") + theme_minimal() +
  ylim(0,0.73)

ener_protest_will <- ggplot(data %>% dplyr::filter(wave==3), aes(ener_will_english)) + 
geom_bar(aes(y = after_stat((..count..)/sum(..count..))), stat= "count") + 
geom_text(aes(label = after_stat(scales::percent((..count..)/sum(..count..),
                                                 accuracy = 1)),
            y= after_stat(((..count..)/sum(..count..)))), stat="count",
        vjust = -.25) + ylab("") + xlab("Ukraine crisis; December 2022/January 2023") + theme_minimal() +
  ylim(0,0.73)


cor_protest_will | ener_protest_will 

rm(cor_protest_will, ener_protest_will)

```


## Table 7: Willingness to participate at the protest among trust groups

```{r results='asis'}

cor_protest_some <- data %>% dplyr::filter(wave==1) %>%
  group_by(trust_government_bins) %>% 
  summarise(count = n(),
            willingness = sum(cor_will_english=="3. (Very) Likely")) %>% 
  mutate(share = willingness/count*100,
         wave = "COVID-19 crisis")
  



ener_protest_some <- data %>% dplyr::filter(wave==3) %>%
  group_by(trust_government_bins) %>% 
  summarise(count = n(),
            willingness = sum(ener_will_english=="3. (Very) Likely")) %>% 
  mutate(share = willingness/count*100, 
         wave = "Ukraine crisis")

bind_rows(cor_protest_some, ener_protest_some) %>% 
  dplyr::relocate(wave) %>% 
  kable()

rm(cor_protest_some, ener_protest_some)

```



##  Regression analyses 1: Consequences of political trust
###  Models on sympathy with and willingness to protest


```{r echo=TRUE, warning=FALSE, message=FALSE}
fit_1.3_cor <- glm(cor.protest_understanding.bin ~  gender + poly(age, 2) + educ_category + current_econ.situation +
                     children.dummy + east_d +
                     poly(left_right, 2) +
                trust_government, data = data.w1, family = "binomial")
```

```{r echo=T, warning=FALSE, message=FALSE}
fit_1.3_w2_ec <- glm(ener.protest_understanding.bin ~  gender + poly(age, 2) + educ_category + current_econ.situation +
                       children.dummy + east_d +
                       poly(left_right, 2) +
                trust_government, data = data.w2, family = "binomial")
```

```{r echo=T, warning=FALSE, message=FALSE}
fit_1.3_cor.p <- glm(cor.protest_willingness.bin ~  gender + poly(age, 2) + educ_category + current_econ.situation + 
                       children.dummy + east_d +
                       poly(left_right, 2) +
                trust_government, data = data.w1, family = "binomial")
```

```{r echo=T, warning=FALSE, message=FALSE}
fit_1.3_w2_ec.p <- glm(ener.protest_willingness.bin ~  gender + poly(age, 2) + educ_category + current_econ.situation +
                         children.dummy + east_d +
                         poly(left_right, 2) +
                trust_government, data = data.w2, family = "binomial")
```


### Predicet probability numbers mentioned in the article

```{r echo=T, warning=FALSE, message=FALSE, fig.height=6, fig.width=7}

ggeffect(fit_1.3_cor)$trust_government %>% 
  as.data.frame() %>% 
  dplyr::rename("Trust level" = x, "Independent variable" = group, "Probability" = predicted) %>%
  kable(caption = "Probability of sympathy with Covid-19 protest")

```

```{r echo=T, warning=FALSE, message=FALSE, fig.height=6, fig.width=7}
ggeffect(fit_1.3_cor.p)$trust_government %>% 
  as.data.frame() %>% 
  dplyr::rename("Trust level" = x, "Independent variable" = group, "Probability" = predicted) %>%
  kable(caption = "Probability of willingness to participate at Covid-19 protest")
```

```{r echo=T, warning=FALSE, message=FALSE, fig.height=6, fig.width=7}
ggeffect(fit_1.3_w2_ec)$trust_government %>% 
  as.data.frame() %>% 
  dplyr::rename("Trust level" = x, "Independent variable" = group, "Probability" = predicted) %>%
  kable(caption = "Probability of sympathy with energy protest")

```

```{r echo=T, warning=FALSE, message=FALSE, fig.height=6, fig.width=7}
ggeffect(fit_1.3_w2_ec.p)$trust_government %>% 
  as.data.frame() %>% 
  dplyr::rename("Trust level" = x, "Independent variable" = group, "Probability" = predicted) %>%
  kable(caption = "Probability of willingness to participate at energy protest")
```


## Figure 3: Political distrust and political protest


```{r echo=T, warning=FALSE, message=FALSE, fig.height=6, fig.width=7}
(effect_plot(fit_1.3_cor, pred = trust_government, interval = TRUE) + 
  ylab("Sympathy for\nthe Protest") + 
  theme_bw() + xlab("") + ggtitle("COVID-19 crisis") + ylim(-0,1) +
  theme(plot.title = element_text(size = 10)) |
  
  effect_plot(fit_1.3_w2_ec, pred = trust_government, interval = TRUE) + 
  ylab("") + 
  theme_bw() + xlab("") + ggtitle("Ukraine crisis") + ylim(-0,1) +
    theme(plot.title = element_text(size = 10)) ) /
  
(effect_plot(fit_1.3_cor.p, pred = trust_government, interval = TRUE) + 
  ylab("Willingness to\nProtest") + 
  theme_bw() + xlab("Trust in the\nFederal Government") + ggtitle("") + ylim(-0,1) +
  theme(plot.title = element_text(size = 10)) |
   
effect_plot(fit_1.3_w2_ec.p, pred = trust_government, interval = TRUE) + 
  ylab("") + 
  theme_bw() + xlab("Trust in the\nFederal Government") + ggtitle("") + ylim(-0,1) +
  theme(plot.title = element_text(size = 10)) 
   )  


ggsave(filename="visualizations/figure_3_manuscript.jpeg",
       plot=last_plot(), device="png", units="cm", width=14, height=12, dpi=300)


```

## Table 8: Regression analysis of Figure 3 – Disposition to Protest

```{r echo=T, results='asis'}   

stargazer(fit_1.3_cor, fit_1.3_w2_ec, fit_1.3_cor.p, fit_1.3_w2_ec.p,
          type = "html",
          single.row = T,
          digits=2,
          digits.extra = 0,
          title="Political Consequences of Trust in Government",
          header = FALSE, column.labels = c(),
          covariate.labels=c("Gender", "Age", "Age2", "Education high", "Education middle",
                             "Cur. Econ. Situation", "Children", "East Germany",
                             "Left-Right","Left-Right2",
                             "Trust Government"),
          dep.var.labels = c("Sympathy: COVID-19 protest", "Sympathy: energy protest",
                             "Willingness: protest at Covid-19 protest", "Willingness: protest at energy protest"),
          font.size= "small",  column.sep.width = "0.5pt")

rm(fit_1.3_cor, fit_1.3_w2_ec, fit_1.3_cor.p, fit_1.3_w2_ec.p)

```



## Correlation test trsut in parliament and trust in government

Strong correlations between trust in parliament and trust in the government in both survey waves

```{r, echo=T, eval = FALSE}       
options(scipen = 999)
cor.test(data.w1$trust_government, data.w1$trust_parliament)
cor.test(data.w2$trust_government, data.w2$trust_parliament)

```


## Regression analysis 2: Determinants of trust in government


```{r, echo=T}

fit_lr       <- lm(trust_government ~  gender + poly(age, 2) + educ_category + current_econ.situation + children.dummy + east_d  +
                     poly(left_right, 2), data = data.w1)

fit_wave2_lr <- lm(trust_government ~  gender + poly(age, 2) + educ_category + current_econ.situation + children.dummy + east_d  +
                     poly(left_right, 2), data = data.w2)

fit_factors       <- lm(trust_government ~  gender + poly(age, 2) + educ_category + current_econ.situation + children.dummy + east_d  +
                          pro_migration_limit + 
                          pro_homosexual_lifestyle +
                          anti_state_intervention.economy, data = data.w1)

fit_wave2_factors <- lm(trust_government ~  gender + poly(age, 2) + educ_category + current_econ.situation + children.dummy + east_d  +
                          pro_migration_limit + 
                          pro_homosexual_lifestyle +
                          anti_state_intervention.economy, data = data.w2)

```


## Table 2: Political correlates of trust in government (selected vars; full Table 10 in SuppMat)

```{r echo=T, results='asis'}       
stargazer(list(fit_lr, fit_wave2_lr, fit_factors, fit_wave2_factors), type = "html",
          single.row = T,
          digits=2,
          digits.extra = 0,
          header = FALSE,
          column.labels = c("Covid-19 crisis", "Ukraine crisis", "Covid-19 crisis", "Ukraine crisis"),
          covariate.labels=c("Female/diverse", "Age", "Age2", "Education high", "Education middle",
                             "Cur. Econ. Situation Sitation", "Children", "East Germany",
                             "Left-Right","Left-Right 2"),
                              dep.var.labels = c("Trust in the Federal Government"),
           font.size= "small",  column.sep.width = "0.5pt")

rm(fit_factors, fit_wave2_factors)
```


## Regression analysis 3: Political party determinants of trust in government

```{r, echo=FALSE}

fit_party <- lm(trust_government ~  gender + poly(age, 2) + educ_category + current_econ.situation + children.dummy + east_d +
                  party_ideology.spd, data = data.w1)

fit_wave2_party <- lm(trust_government ~  gender + poly(age, 2) + educ_category + current_econ.situation + children.dummy + east_d +
                        party_ideology.spd, data = data.w2)

```


## Table 11: Regression analysis of Figure 5 – Political trust in government across partisan groups

```{r echo=T, results='asis'}  

stargazer(list(fit_party, fit_wave2_party), type = "html",
          single.row = T,
          digits=2,
          digits.extra = 0,
          header = FALSE,
          column.labels = c("Covid-19 crisis", "Ukraine crisis"),
          covariate.labels=c("Female/diverse", "Age", "Age2", "Education high", "Education middle",
                             "Cur. econ. situation", "Children", "Eastern Germany",
                             "not represented", "don't know",
                             "AfD","Die Linke","FDP","CDU/CSU",
                             "Bündnis 90/Die Grünen"),
                              dep.var.labels = c("Trust in the Federal Government"),
           font.size= "small",  column.sep.width = "0.5pt")


```


## Figure 5: Political trust in government across partisan groups 


```{r, echo=T, results='asis', warning=F, message=F, fig.width=8}       

party_predicted <- ggpredict(fit_party, terms = c("party_ideology.spd")) %>% 
  as.data.frame() %>% mutate(wave = "COVID-19 crisis")

party_predicted2 <- ggpredict(fit_wave2_party, terms = c("party_ideology.spd")) %>% 
  as.data.frame() %>% mutate(wave = "Ukraine crisis")

party_predicted <- party_predicted %>% bind_rows(party_predicted2) %>% 
    mutate(wave_char = factor(wave, levels = c("Ukraine crisis", "COVID-19 crisis")))

rm(party_predicted2)


party_predicted <- party_predicted %>% 
  mutate(party_ideology.fc.new =
           case_when(
             as.character(x) == "weiß nicht" ~ "don't know",
             as.character(x) == "nicht repräsentiert" ~ "not represented",
             TRUE ~ as.character(x)
           )) 

party_mean.order <- party_predicted %>% arrange((predicted)) %>% dplyr::select(party_ideology.fc.new) %>% 
  dplyr::filter(!duplicated(party_ideology.fc.new)) 

party_predicted <- party_predicted %>% 
  mutate(party_ideology.fc.new.new = factor(party_ideology.fc.new,
                                    levels = party_mean.order$party_ideology.fc.new))


ggplot(party_predicted, aes(party_ideology.fc.new.new, predicted )) +
      geom_pointrange(aes(ymin = conf.low, ymax = conf.high,
                        shape=wave_char),  size = 0.7,
                      position=position_dodge(0.6), 
                    linetype='solid') + scale_y_continuous(expand = c(0, 0), limits = c(-0.5,10.5)) +
    theme_minimal() + xlab("") + ylab("Trust in government (predicted values)") +
  labs(shape = "") + coord_flip()

ggsave(filename="visualizations/figure_5_manuscript.jpeg",
       plot=last_plot(), device="png", units="cm", width=20, height=8, dpi=300)


rm(party_mean.order, party_predicted)

```

## Figure 14: Predicted trust based on age 2nd polynomial, Models 1 and 3 in Table 1


```{r, echo=T, warning=FALSE, message=FALSE}
effect_plot(fit_lr, pred = age, interval = TRUE, data = data.w1, rug = TRUE) + theme_bw() + 
  ylab("Predicted trust in Government") + xlab("Age (quadratic)") +
  ggtitle("COVID-19 crisis") |

effect_plot(fit_wave2_lr, pred = age, interval = TRUE, data = data.w2, rug = TRUE) + theme_bw() + 
  ylab("Predicted trust in Government") + xlab("Age (quadratic)") + ggtitle("Ukraine crisis")


```

## Figure 15: Predicted trust based on left-right 2nd polynomial, Models 1 and 3 in Table 1

```{r, echo=T, warning=FALSE, message=FALSE}
effect_plot(fit_lr, pred = left_right, interval = TRUE, data = data.w1, rug = TRUE) + theme_bw() + 
  ylab("Predicted trust in Government") + xlab("Left-Right (quadratic)") +
  ggtitle("COVID-19 crisis") |
effect_plot(fit_wave2_lr, pred = left_right, interval = TRUE, data = data.w2, rug = TRUE) + theme_bw() + 
  ylab("Predicted trust in Government") + xlab("Left-Right (quadratic)") +
  ggtitle("Ukraine crisis") 

rm(fit_lr, fit_wave2_lr, fit_party, fit_wave2_party)

```

## Figure 16: Trust across left-right, smoothed means

```{r, echo=T, warning=FALSE, message=FALSE}
ggplot(data.w1, aes(x=left_right, y=trust_government)) +
  geom_smooth(color = "black") + theme_bw() + 
  ylab("Trust in Government") + xlab("Left-Right") + ggtitle("COVID-19 crisis") |
  
ggplot(data.w2, aes(x=left_right, y=trust_government)) +
  geom_smooth(color = "black") + theme_bw() +
  ylab("Trust in Government") + xlab("Left-Right") + ggtitle("Ukraine crisis") 

```


## Regression analysis 4: 'democratic deficit'


```{r}

fit_1.4 <- lm(pol_deprivation ~  gender + age + educ_category + current_econ.situation + children.dummy + east_d + 
                left_right + trust_government, data = data.w1)

fit_1.4_w2 <- lm(pol_deprivation ~  gender + age + educ_category + current_econ.situation + children.dummy + east_d + 
                   left_right + trust_government, data = data.w2)

fit_1.4_demo <- lm(satisfaction_german.democracy ~  gender + age + educ_category + current_econ.situation + 
                     children.dummy + east_d + 
                left_right + trust_government, data = data.w1)

fit_1.4_w2_demo <- lm(satisfaction_german.democracy ~  gender + age + educ_category + current_econ.situation +
                        children.dummy + east_d + 
                   left_right + trust_government, data = data.w2)

fit_1.4_ref <- lm(pro_referenda_binding ~  gender + age + educ_category + current_econ.situation + children.dummy + 
                    east_d + 
                left_right + trust_government, data = data.w1)

fit_1.4_w2_ref <- lm(pro_referenda_binding ~  gender + age + educ_category + current_econ.situation + children.dummy +
                       east_d + 
                   left_right + trust_government, data = data.w2)

```


## Table 1 (selecteed vars), part 1 (full Table 9 in SuppMat)

```{r echo=T, results='asis'}   
stargazer(fit_1.4, fit_1.4_w2, fit_1.4_demo, fit_1.4_w2_demo, type = "html",
          single.row = T,
          digits=2,
          digits.extra = 0,
          header = FALSE,
          column.labels = c("Covid-19 crisis", "Ukraine crisis", "Covid-19 crisis", "Ukraine crisis"),
          covariate.labels=c("Gender", "Age", "Education high", "Education middle",
                             "Cur. Econ. Situation", "Children", "East Germany",
                             "Left-Right","Trust Fed. Gov."),
          dep.var.labels = c("Political Deprivation", "Satisfaction with German Democracy"),
          font.size= "small",  column.sep.width = "0.5pt")

rm(fit_1.4, fit_1.4_w2, fit_1.4_demo, fit_1.4_w2_demo)

```

## Table 1 (selecteed vars), part 2 (full Table 9 in SI)

```{r echo=T, results='asis'}   
stargazer(fit_1.4_ref, fit_1.4_w2_ref,  type = "html",
          single.row = T,
          digits=2,
          digits.extra = 0,
          header = FALSE,
          column.labels = c("Covid-19 crisis", "Ukraine crisis"),
          covariate.labels=c("Gender", "Age", "Education high", "Education middle",
                             "Cur. Econ. Situation", "Children", "East Germany",
                             "Left-Right","Trust Fed. Gov."),
          dep.var.labels = c("Pro Referenda Binding", "Pro Referenda Binding"),
          font.size= "small",  column.sep.width = "0.5pt")


rm(fit_1.4_ref, fit_1.4_w2_ref)

```


## Figure 8: Cluster analysis of k-means for trust group identification 

```{r fig.width=8}

data$trust_factor <- factor(data$trust_government)
data$wave_factor <- factor(data$wave)

kmeans_pol_deprivation <- glm(pol_deprivation ~ trust_factor + wave, data = data)
kmeans_pro_referenda_binding <- glm(pro_referenda_binding ~ trust_factor + wave, data = data)
kmeans_satisfaction_german.democracy <- glm(satisfaction_german.democracy ~ trust_factor + wave, data = data)

# Get predictions and confidence intervals
predictions_pol_deprivation <- predict(kmeans_pol_deprivation, type = "response")
predictions_pro_referenda_binding <- predict(kmeans_pro_referenda_binding, type = "response")
predictions_satisfaction_german.democracy <- predict(kmeans_satisfaction_german.democracy, type = "response")

data_with_predictions <- data.frame(
  trust_factor = as.numeric(levels(data$trust_factor))[data$trust_factor],
  predictions_pol_deprivation = predictions_pol_deprivation,
  predictions_pro_referenda_binding = predictions_pro_referenda_binding,
  predictions_satisfaction_german.democracy = predictions_satisfaction_german.democracy)

set.seed(1234)  # For reproducibility
data_with_predictions$cluster_pol_deprivation <- kmeans(data_with_predictions$predictions_pol_deprivation,
                                                        centers = 3)$cluster
data_with_predictions$cluster_pro_referenda_binding <- kmeans(data_with_predictions$predictions_pro_referenda_binding,
                                                              centers = 3)$cluster  
data_with_predictions$cluster_satisfaction_german.democracy <-
  kmeans(data_with_predictions$predictions_satisfaction_german.democracy,
                                                                      centers = 3)$cluster  

cluster_colors <- c("grey", "#800000", "#000099") # black, redwine (maroon), and darkblue



# Plotting the results with custom cluster colors
k_depri <- ggplot(data_with_predictions, aes(x = trust_factor, y = predictions_pol_deprivation,
                                             color = factor(cluster_pol_deprivation))) +
  geom_point(size = 3.5) +
  labs(y = "Predicted Political Deprivation", x = "Trust in government",
       color = "Cluster") +
  scale_color_manual(values = c("grey", "#800000", "#000099")) + # Apply custom colors
  theme_minimal() +
  theme(legend.position = "none")

kk_demo <- ggplot(data_with_predictions, 
                  aes(x = trust_factor, y = predictions_satisfaction_german.democracy, 
                      color = factor(cluster_satisfaction_german.democracy))) +
  geom_point(size = 3.5) +
  labs(y = "Predicted Satisfaction\nw. Democracy", x = "Trust in government",
       color = "Cluster") +
  scale_color_manual(values = c("#800000", "grey", "#000099")) + # Apply custom colors
  theme_minimal() +
  theme(legend.position = "bottom")

k_dd <- ggplot(data_with_predictions, aes(x = trust_factor, y = predictions_pro_referenda_binding, 
                                          color = factor(cluster_pro_referenda_binding))) +
  geom_point(size = 3.5) +
  labs(y = "Predicted Pro Direct Democracy", x = "Trust in government",
       color = "Cluster") +
  scale_color_manual(values = c("#000099", "#800000", "grey")) + # Apply custom colors
  theme_minimal() +
  theme(legend.position = "none")

k_depri | kk_demo | k_dd

rm(k_depri, kk_demo, k_dd, kmeans_satisfaction_german.democracy,
   kmeans_pro_referenda_binding, kmeans_pol_deprivation,
   cluster_colors, predictions_pro_referenda_binding, predictions_satisfaction_german.democracy,
   predictions_pol_deprivation)
```


## Figure 23: Political trust, ideology, and extremism

```{r fig.width=8, fig.height=6, echo=T, warning=FALSE, message=FALSE}

extremism_w1 <- ggscatter(data.w1, x = "extremisms_lr", y = "trust_government", 
          add = "reg.line", conf.int = TRUE, 
          cor.coef = TRUE, cor.method = "pearson",
          xlab = "Extremism scale", ylab = "Trust in government")

extremism_w2 <- ggscatter(data.w2, x = "extremisms_lr", y = "trust_government", 
          add = "reg.line", conf.int = TRUE, 
          cor.coef = TRUE, cor.method = "pearson",
          xlab = "Extremism scale", ylab = "Trust in government")


lr_w1 <- ggscatter(data.w1, x = "left_right", y = "trust_government", 
          add = "reg.line", conf.int = TRUE, title = "COVID-19 crisis",
          cor.coef = TRUE, cor.method = "pearson",
          xlab = "Left-right scale", ylab = "Trust in government")

lr_w2 <- ggscatter(data.w2, x = "left_right", y = "trust_government", 
          add = "reg.line", conf.int = TRUE, title = "Ukraine crisis",
          cor.coef = TRUE, cor.method = "pearson",
          xlab = "Left-right scale", ylab = "Trust in government")

(lr_w1 | lr_w2) / (extremism_w1 | extremism_w2)

rm(extremism_w1, extremism_w2, lr_w1, lr_w2)
```



## PARL Regression analysis 5: Political consequences of trust in parliament

### Models on sympathy with and willingness to protest


```{r echo=T, warning=FALSE, message=FALSE}

fit_1.3_cor.parl <- glm(cor.protest_understanding.bin ~  gender + poly(age, 2) + educ_category + current_econ.situation + children.dummy + east_d + poly(left_right, 2) +
                trust_parliament, data = data.w1, family = "binomial")

fit_1.3_w2_ec.parl <- glm(ener.protest_understanding.bin ~  gender + poly(age, 2) + educ_category + current_econ.situation + children.dummy + east_d + poly(left_right, 2) +
                trust_parliament, data = data.w2, family = "binomial")

fit_1.3_cor.p.parl <- glm(cor.protest_willingness.bin ~  gender + poly(age, 2) + educ_category + current_econ.situation + children.dummy + east_d + poly(left_right, 2) +
                trust_parliament, data = data.w1, family = "binomial")

fit_1.3_w2_ec.p.parl <- glm(ener.protest_willingness.bin ~  gender + poly(age, 2) + educ_category + current_econ.situation + children.dummy + east_d + poly(left_right, 2) +
                trust_parliament, data = data.w2, family = "binomial")

```


## Table 13, part 1: Table 13: Regression analysis of Figure 21 in Online Appendix A.7

```{r echo=T, results='asis'}   
stargazer(fit_1.3_cor.parl, fit_1.3_w2_ec.parl, 
           type = "html",
          single.row = T,
          digits=2,
          digits.extra = 0,
          title="Political Consequences of Trust in Parliament", 
          header = FALSE, 
          covariate.labels=c("Gender", "Age", "Age2", "Education high", "Education middle",
                             "Cur. Econ. Situation", "Children", "East Germany",
                             "Left-Right","Left-Rigth 2",
                             "Trust Parliament"),
          dep.var.labels = c("Sympathy: COVID-19 protest", "Sympathy: energy protest"),
          font.size= "small",  column.sep.width = "0.5pt")
```


## Table 13, part 2: Table 13: Regression analysis of Figure 21 in Online Appendix A.7

```{r echo=FALSE, results='asis'}   
stargazer(fit_1.3_cor.p.parl, fit_1.3_w2_ec.p.parl,
           type = "html",
          single.row = T,
          digits=2,
          digits.extra = 0,
          title="Political Consequences of Trust in Parliament", 
          header = FALSE, 
          covariate.labels=c("Gender", "Age", "Age2", "Education high", "Education middle",
                             "Cur. Econ. Situation", "Children", "East Germany",
                             "Left-Right","Left-Rigth 2",
                             "Trust Parliament"),
          dep.var.labels = c("Willingness: protest at Covid-19 protest", "Willingness: protest at energy protest"),
          font.size= "small",  column.sep.width = "0.5pt")


```

## Figure 21: Political distrust in parliament and political protest

```{r message = FALSE, warning = FALSE}


(effect_plot(fit_1.3_cor.parl, pred = trust_parliament, interval = TRUE) + 
  ylab("Sympathy for\nthe Protest") + 
  theme_bw() + xlab("") + ggtitle("COVID-19 crisis") + ylim(-0,1) +
  theme(plot.title = element_text(size = 10)) |
  
  effect_plot(fit_1.3_w2_ec.parl, pred = trust_parliament, interval = TRUE) + 
  ylab("") + 
  theme_bw() + xlab("") + ggtitle("Ukraine crisis") + ylim(-0,1) +
    theme(plot.title = element_text(size = 10)) ) /
  
(effect_plot(fit_1.3_cor.p.parl, pred = trust_parliament, interval = TRUE) + 
  ylab("Willingness to\nProtest") + 
  theme_bw() + xlab("Trust in the\nParliament") + ggtitle("") + ylim(-0,1) +
  theme(plot.title = element_text(size = 10)) |
   
effect_plot(fit_1.3_w2_ec.p.parl, pred = trust_parliament, interval = TRUE) + 
  ylab("") + 
  theme_bw() + xlab("Trust in the\nParliament") + ggtitle("") + ylim(-0,1) +
  theme(plot.title = element_text(size = 10)) 
   )  


rm(fit_1.3_cor.parl, fit_1.3_w2_ec.parl, fit_1.3_cor.p.parl, fit_1.3_w2_ec.p.parl)

```




## PARL Regression analysis 6: Determinants of trust in parliament

### Models on political correlates of trust in government


```{r, echo=T}

fit_lr.parl       <- lm(trust_parliament ~  gender + poly(age, 2) + educ_category + current_econ.situation + 
                          children.dummy + east_d  +
                          poly(left_right, 2), data = data.w1)
fit_wave2_lr.parl <- lm(trust_parliament ~  gender + poly(age, 2) + educ_category + current_econ.situation + 
                          children.dummy + east_d  +
                          poly(left_right, 2), data = data.w2)

fit_factors.parl       <- lm(trust_parliament ~  gender + poly(age, 2) + educ_category + current_econ.situation +
                               children.dummy + east_d  +
                               pro_migration_limit + 
                               pro_homosexual_lifestyle +
                               anti_state_intervention.economy, data = data.w1)

fit_wave2_factors.parl <- lm(trust_parliament ~  gender + poly(age, 2) + educ_category + 
                               current_econ.situation + children.dummy + east_d  +
                               pro_migration_limit + 
                               pro_homosexual_lifestyle +
                               anti_state_intervention.economy, data = data.w2)

```


## Table 15: Socio-demographic and political determinants of trust in parliament

```{r echo=T, results='asis'}       
stargazer(list(fit_lr.parl, fit_wave2_lr.parl, fit_factors.parl, fit_wave2_factors.parl), type = "html",
          single.row = T,
          digits=2,
          digits.extra = 0,
          header = FALSE,
          column.labels = c("Covid-19 crisis", "Ukraine crisis", "Covid-19 crisis", "Ukraine crisis"),
          covariate.labels=c("Female/diverse", "Age", "Age2", "Education high", "Education middle",
                             "Cur. Econ. Situation Sitation", "Children", "East Germany",
                             "Left-Right","Left-Right 2"),
                              dep.var.labels = c("Trust in the Parliament"),
           font.size= "small",  column.sep.width = "0.5pt")

rm(fit_lr.parl, fit_wave2_lr.parl, fit_factors.parl, fit_wave2_factors.parl)

```

### Models on political party determinants of trust in parliament

```{r, echo=T}

fit_party.parl <- lm(trust_parliament ~  gender + poly(age, 2) + educ_category + current_econ.situation + children.dummy + east_d + party_ideology.spd, data = data.w1)

fit_wave2_party.parl <- lm(trust_parliament ~  gender + poly(age, 2) + educ_category + current_econ.situation + children.dummy + east_d + party_ideology.spd, data = data.w2)

```


## Table 16: Political trust in parliament across partisan groups

```{r echo=T, results='asis'}  
stargazer(list(fit_party.parl, fit_wave2_party.parl), type = "html",
          single.row = T,
          digits=2,
          digits.extra = 0,
          header = FALSE,
          column.labels = c("Covid-19 crisis", "Ukraine crisis"),
          covariate.labels=c("Female/diverse", "Age", "Age2", "Education high", "Education middle",
                             "Cur. econ. situation", "Children", "Eastern Germany",
                             "not represented", "don't know",
                             "AfD","Die Linke","FDP","CDU/CSU",
                             "Bündnis 90/Die Grünen"),
                              dep.var.labels = c("Trust in the Parliament"),
           font.size= "small",  column.sep.width = "0.5pt")
```



## Figure 22: Political trust in parliament across partisan groups based on Table 16

```{r, echo=F, results='asis', warning=F, message=F, fig.width=8}       

party_predicted.parl <- ggpredict(fit_party.parl, terms = c("party_ideology.spd")) %>% 
  as.data.frame() %>% mutate(wave = "COVID-19 crisis")

party_predicted2.parl <- ggpredict(fit_wave2_party.parl, terms = c("party_ideology.spd")) %>% 
  as.data.frame() %>% mutate(wave = "Ukraine crisis")

party_predicted.parl <- party_predicted.parl %>% bind_rows(party_predicted2.parl) %>% 
    mutate(wave_char = factor(wave, levels = c("Ukraine crisis", "COVID-19 crisis")))

rm(party_predicted2.parl)



party_predicted.parl <- party_predicted.parl %>% 
  mutate(party_ideology.fc.new =
           case_when(
             as.character(x) == "weiß nicht" ~ "don't know",
             as.character(x) == "nicht repräsentiert" ~ "not represented",
             TRUE ~ as.character(x)
           )) 

party_mean.order.parl <- party_predicted.parl %>% arrange((predicted)) %>%
  dplyr::select(party_ideology.fc.new) %>% 
  dplyr::filter(!duplicated(party_ideology.fc.new)) 

party_predicted.parl <- party_predicted.parl %>% 
  mutate(party_ideology.fc.new.new = factor(party_ideology.fc.new,
                                    levels = party_mean.order.parl$party_ideology.fc.new))

ggplot(party_predicted.parl, aes(party_ideology.fc.new.new, predicted )) +
      geom_pointrange(aes(ymin = conf.low, ymax = conf.high,
                        shape=wave_char),  size = 0.7,
                      position=position_dodge(0.6), 
                    linetype='solid') + scale_y_continuous(expand = c(0, 0), limits = c(-0.5,10.5)) +
    theme_minimal() + xlab("") + ylab("Trust in parliament (predicted values)") +
  labs(shape = "") + coord_flip()

rm(party_predicted.parl, party_mean.order.parl,
   fit_party.parl, fit_wave2_party.parl)

```


## PARL Regression analysis 7: 'democratic deficit'


### Models on political deprivation, satisfaction with democracy, and support for referenda

```{r}

fit_1.4.parl <- lm(pol_deprivation ~  gender + age + educ_category + current_econ.situation + children.dummy + east_d + 
                left_right + trust_parliament, data = data.w1)

fit_1.4_w2.parl <- lm(pol_deprivation ~  gender + age + educ_category + current_econ.situation + children.dummy +
                        east_d + 
                   left_right + trust_parliament, data = data.w2)

fit_1.4_demo.parl <- lm(satisfaction_german.democracy ~  gender + age + educ_category + current_econ.situation +
                          children.dummy + east_d + 
                left_right + trust_parliament, data = data.w1)

fit_1.4_w2_demo.parl <- lm(satisfaction_german.democracy ~  gender + age + educ_category + current_econ.situation +
                             children.dummy + east_d + 
                   left_right + trust_parliament, data = data.w2)


fit_1.4_ref.parl <- lm(pro_referenda_binding ~  gender + age + educ_category + current_econ.situation + children.dummy +
                         east_d + 
                left_right + trust_parliament, data = data.w1)

fit_1.4_w2_ref.parl <- lm(pro_referenda_binding ~  gender + age + educ_category + current_econ.situation + children.dummy + east_d + 
                   left_right + trust_parliament, data = data.w2)

```


## Table 14, part 1: Attitudinal correlates of political trust in parliament

```{r echo=T, results='asis'}   
stargazer(fit_1.4.parl, fit_1.4_w2.parl, fit_1.4_demo.parl, fit_1.4_w2_demo.parl, type = "html",
          single.row = T,
          digits=2,
          digits.extra = 0,
          header = FALSE,
          column.labels = c("Covid-19 crisis", "Ukraine crisis", "Covid-19 crisis", "Ukraine crisis"),
          covariate.labels=c("Gender", "Age", "Education high", "Education middle",
                             "Cur. Econ. Situation", "Children", "East Germany",
                             "Left-Right","Trust Parliament"),
          dep.var.labels = c("Political Deprivation", "Satisfaction with German Democracy"),
          font.size= "small",  column.sep.width = "0.5pt")

```

## Table 14, part 2: Attitudinal correlates of political trust in parliament

```{r echo=F, results='asis'}   
stargazer(fit_1.4_ref.parl, fit_1.4_w2_ref.parl,  type = "html",
          single.row = T,
          digits=2,
          digits.extra = 0,
          header = FALSE,
          column.labels = c("Covid-19 crisis", "Ukraine crisis"),
          covariate.labels=c("Gender", "Age", "Education high", "Education middle",
                             "Cur. Econ. Situation", "Children", "East Germany",
                             "Left-Right","Trust Parliament"),
          dep.var.labels = c("Pro Referenda Binding"),
          font.size= "small",  column.sep.width = "0.5pt")


```
```{r}
# Clean environment

rm(fit_1.4.parl, fit_1.4_w2.parl, fit_1.4_demo.parl, fit_1.4_w2_demo.parl,
   fit_1.4_ref.parl, fit_1.4_w2_ref.parl)
```



## Figure 4: Democratic beliefs and evaluation of democracy in Germany

```{r fig.width=9, fig.height=7, echo=T, warning=FALSE, message=FALSE}

# Predicted values instead based on OLS regressions

outcome_vars <- c(
  "democracygen_courtequality", "democracygen_minortyrights", "democracygen_mediacritique",
  "democracygen_fairelections", "democracygen_punishincumbent", "democracygen_partydifference",
  "democracyger_courtequality", "democracyger_minortyrights", "democracyger_mediacritique",
  "democracyger_fairelections", "democracyger_punishincumbent", "democracyger_partydifference"
)

# Initialize an empty list to store results
results_list <- list()

# Loop over each outcome variable
for (outcome in outcome_vars) {
  # Run the regression
  fit <- lm(as.formula(paste(outcome,
                             "~ gender + age + educ_category + current_econ.situation + children.dummy + east_d + left_right + trust_government_bins.fc")),
            data = data)
  
  # Get the predicted values using ggeffect
  ggeffect_data <- ggeffect(fit, terms = "trust_government_bins.fc") %>%
    as.data.frame() %>%
    mutate(outcome_variable = outcome)
  
  # Store the results in the list
  results_list[[outcome]] <- ggeffect_data
}

rm(fit, ggeffect_data, outcome, outcome_vars)

# Combine all results into a single data frame
final_results <- bind_rows(results_list)
rm(results_list)

final_results <- final_results %>% 
  mutate(category = if_else(grepl("ger[_]", outcome_variable), "Democracy in Germany entails...",
                            "Democracy should entail...")) %>% 
  mutate(element = case_when(grepl("courtequality", outcome_variable) ~ "liberal: equality before the law",
                             grepl("fairelections", outcome_variable) ~ "electoral: free and fair elections",
                             grepl("mediacritique", outcome_variable) ~ "liberal: media freedom",
                             grepl("minortyrights", outcome_variable) ~ "liberal: minority protection",
                             grepl("partydifference", outcome_variable) ~ "electoral: electoral competition",
                             grepl("punishincumbent", outcome_variable) ~ "electoral: vertical accountability",))

ggplot(final_results) + 
      geom_pointrange(aes(x = x, 
                      y = predicted, 
                      ymin = conf.low, 
                      ymax = conf.high, 
                      group = category, 
                      fill = category), 
                  shape = 21, size = 0.4) +
  facet_wrap(~ element) +
  ylim(2,10) +
  #scale_fill_manual(values=c("white", "black")) +
  ylab("'Democracy should entail' vs\n'Democracy in Germany entails', Predicted values") +
  xlab("") + theme(legend.position="bottom") +
  theme(legend.title=element_blank())

ggsave(filename="visualizations/figure_4_manuscript.jpeg",
       plot=last_plot(), device="png", units="cm", width=20, height=19, dpi=300)

rm(final_results)

```

# Time Series Analysis

## Figure 1: Trust in the German Federal government, 2020-2023

```{r fig.width=8, fig.height=5, message = FALSE, warning = FALSE}

ts_wave1 <- data.w1 %>% dplyr::select(trust_government, trust_parliament) %>% mutate(date_month = "2022-02-15")
ts_wave2 <- data.w2 %>% dplyr::select(trust_government, trust_parliament) %>% mutate(date_month = "2023-01-01")

time_series <- time_series %>% bind_rows(ts_wave1, ts_wave2) %>% 
  mutate(date_month = as.Date(date_month))

time_series.sum <- time_series %>%
  mutate(trust_level = case_when(trust_government==0 ~ "No trust",
                                 trust_government>=1 & trust_government<=5 ~ "Low trust",
                                 trust_government>=6 & trust_government<=10 ~ "High trust")) %>% 
  group_by(date_month, trust_level) %>% 
  summarise(level_sum = n()) %>% arrange(date_month) %>% 
  ungroup() %>% dplyr::filter(!is.na(trust_level)) %>% 
  group_by(date_month) %>% mutate(total_n = sum(level_sum, na.rm = TRUE)) %>% ungroup() %>% 
  mutate(trust_level_share = level_sum/total_n*100)


time_series.sum %>%
  dplyr::filter(!date_month==as.Date("2023-12-15")) %>% 
  ggplot(aes(y = trust_level_share, x = date_month)) +
  geom_line(size = 1, aes(group = trust_level, color = trust_level, linetype=trust_level)) +
  scale_linetype_manual(values=c("solid","dashed", "dotted")) + 
  scale_color_manual(values=c("black","black","black"))+
  geom_point(size = 2, aes(group = trust_level, color = trust_level)) +
  theme_bw() + ylab("Respondents (%)") + xlab("") +
  theme(legend.position="bottom", legend.box = "horizontal") +
  theme(legend.title = element_blank()) +
  annotate('rect', xmin=as.Date("2022-02-01"), xmax=as.Date("2022-03-01"), ymin=75, ymax=8,
           alpha=.2, fill='gray35') +
  annotate('rect', xmin=as.Date("2022-12-01"), xmax=as.Date("2023-01-01"), ymin=75, ymax=8,
           alpha=.2, fill='gray35')

ggsave(filename="visualizations/figure_1_manuscript.jpeg",
       plot=last_plot(), device="png", units="cm", width=14, height=8, dpi=300)

rm(ts_wave1, ts_wave2)
```


## Figure 7: Aggregated trust in government levels of year-semesters

```{r fig.width=10, fig.height=5, message = FALSE, warning = FALSE}
time_series.sum_year <- time_series.sum %>% 
  mutate(year = lubridate::year(date_month)) %>% 
  group_by(year, trust_level) %>% 
  summarise(trust_avg = mean(trust_level_share, na.rm = TRUE))


time_series.sum <- time_series.sum %>% 
  mutate(period = case_when(date_month<as.Date("2021-01-01") ~ "2020-2",
                            date_month>=as.Date("2021-01-01") & date_month<as.Date("2022-01-02") ~ "2021-1",
                            date_month>=as.Date("2022-01-01") & date_month<as.Date("2022-07-01") ~ "2022-1",
                            date_month>=as.Date("2022-07-01") & date_month<as.Date("2023-01-01") ~ "2022-2",
                            date_month>=as.Date("2023-01-01") & date_month<as.Date("2023-07-01") ~ "2023-1",
                            date_month>=as.Date("2023-07-01")  ~ "2023-2",))



time_series.periods <- time_series.sum %>% dplyr::filter(!date_month==as.Date("2023-12-15")) %>% 
  group_by(period, trust_level) %>% 
  summarise(level = round(mean(trust_level_share, na.rm = TRUE),1))

time_series.periods %>% 
ggplot(aes(x=trust_level, y=level)) + 
  geom_bar(position=position_dodge(), stat="identity", 
           colour='black', width = 0.85, fill = "darkgrey") + 
  #geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.2) +
  xlab("Year-Semester") +  theme_minimal() + ylab("Trust level group share") +
  ggtitle("Trust in government over time") + 
  geom_text(aes(label=level), vjust=3) +
  facet_grid(~period) 


```



# Comparative TS analysis

## Eurobarometer analysis

As reported in the Supplementary Material, we make use of the EB data set by Russo, L. & Bräutigam, M. (2023). Harmonized Eurobarometer 2004-2021. GESIS, Cologne. Data File Version 3.0.0, https://doi.org/10.7802/2539 (https://search.gesis.org/research_data/SDN-10.7802-2539).

Download the data after logging in to the GESIS portal. We do not make an additional data copy available in the Harvard Dataverse repository. For reproducibility reasons, access the originally stored data in the GESIS portal.


```{r message=FALSE, warning=FALSE}
rm(list=ls())

ebm <- haven::read_dta("../../harmonised_EB_2004-2021_v3-0-0.dta/harmonised_EB_2004-2021_v3-0-0.dta") 
ebm <- ebm %>% mutate(country_cl = 
                        case_when(country==4 ~ "Germany",
                                  country==1 ~ "France",
                                  country==3 ~ "Netherlands",
                                  country==5 ~ "Italy",
                                  country==7 ~ "Denmark",
                                  country==9 ~ "Great Britain",
                                  country==15 ~ "Norway",
                                  country==17 ~ "Sweden",
                                  country==18 ~ "Austria"))

ebm <- ebm %>% 
  mutate(trust_parliament = case_when(trms_nparl==1 ~ 1,
                                      trms_nparl==2 ~ 0,
                                      TRUE ~ NA),
         trust_government = case_when(trms_ngov==1 ~ 1,
                                      trms_ngov==2 ~ 0,
                                      TRUE ~ NA))

ebm.trust <- ebm %>% 
  group_by(year, country_cl) %>% 
  summarise(Parliament = mean(trust_parliament, na.rm = TRUE)*100,
            Government = mean(trust_government, na.rm = TRUE)*100) %>% 
  pivot_longer(!c(year, country_cl), names_to = "Institution", values_to = "Trusters share (1)") %>% 
  dplyr::filter(!is.na(country_cl))


```


## Figure 9: Trust in national governments in comparison, Eurobarometer

```{r message=FALSE, warning=FALSE}
(ggplot(data=ebm.trust %>% dplyr::filter(Institution=="Government"),
       aes(x=year, y=`Trusters share (1)`)) + 
  geom_line() +
  ylab("Share (%) people 'tending to trust' (1) vs\nnot tending to trust (0) the National Government") +
  ggtitle("Trust levels in National governments (Eurobarometer)") +
  facet_wrap(~ country_cl) +
  theme(legend.text = element_text(size = 12)) + 
  theme_bw() + ylim(10,90) + xlab("Year")) 

```

## Figure 10: Trust in national parliaments in comparison, Eurobarometer

```{r message=FALSE, warning=FALSE}
(ggplot(data=ebm.trust %>% dplyr::filter(Institution=="Parliament"),
       aes(x=year, y=`Trusters share (1)`)) + 
  geom_line() +
  ylab("Share (%) people 'tending to trust' (1) vs\nnot tending to trust (0) the National Parliament") +
  ggtitle("Trust levels in National Parliament (Eurobarometer)") +
  facet_wrap(~ country_cl) +
  theme(legend.text = element_text(size = 12)) + 
  theme_bw() + ylim(10,90) + xlab("Year"))


```


## ESS analysis


Download the ESS data from the ESS Data Portal (https://ess.sikt.no/en/?tab=builder). We do not make an additional data copy available in the Harvard Dataverse repository. For reproducibility reasons, access the originally stored data in the ESS Data Portal.

We downloaded the 12 waves of the ESS, from 1 to 11 including the additional 10SC wave. We downloaded the full ESS data and filtered the data in the code (for country DE). However, selecting the country Germany and the respective waves in the ESS datafile builder (Wizard) should lead to the exact same data.

Source: European Social Survey European Research Infrastructure (ESS ERIC). (2024). ESS round 11- 2023. Social inequalities in health, Gender in contemporary Europe. Sikt - Norwegian Agency for Shared Services in Education and Research. https://doi.org/10.21338/ess11-2023.


## Figure 11: Trust in the German Federal parliament, European Social Survey (ESS)


```{r message=FALSE, warning=FALSE}

# Load and process data for each wave
ess02 <- read_sav("../../ess/ESS1e06_7/ESS1e06_7.sav") %>%
  filter(cntry == "DE") %>%
  dplyr::select(trstprl) %>%
  mutate(year = 2002)

ess04 <- read_sav("../../ess/ESS2e03_6/ESS2e03_6.sav") %>%
  filter(cntry == "DE") %>%
  dplyr::select(trstprl) %>%
  mutate(year = 2004)

ess06 <- read_sav("../../ess/ESS3e03_7/ESS3e03_7.sav") %>%
  filter(cntry == "DE") %>%
  dplyr::select(trstprl) %>%
  mutate(year = 2006)

ess08 <- read_sav("../../ess/ESS4e04_6/ESS4e04_6.sav") %>%
  filter(cntry == "DE") %>%
  dplyr::select(trstprl) %>%
  mutate(year = 2008)

ess10 <- read_sav("../../ess/ESS5e03_5/ESS5e03_5.sav") %>%
  filter(cntry == "DE") %>%
  dplyr::select(trstprl) %>%
  mutate(year = 2010)

ess12 <- read_sav("../../ess/ESS6e02_6/ESS6e02_6.sav") %>%
  filter(cntry == "DE") %>%
  dplyr::select(trstprl) %>%
  mutate(year = 2012)

ess14 <- read_sav("../../ess/ESS7e02_3/ESS7e02_3.sav") %>%
  filter(cntry == "DE") %>%
  dplyr::select(trstprl) %>%
  mutate(year = 2014)

ess16 <- read_sav("../../ess/ESS8e02_3/ESS8e02_3.sav") %>%
  filter(cntry == "DE") %>%
  dplyr::select(trstprl) %>%
  mutate(year = 2016)

ess18 <- read_sav("../../ess/ESS9e03_2/ESS9e03_2.sav") %>%
  filter(cntry == "DE") %>%
  dplyr::select(trstprl) %>%
  mutate(year = 2018)


ess20 <- read.csv("../../ess/ESS10SC-subset/ESS10SC-subset.csv") %>% 
  filter(cntry == "DE") %>%
  dplyr::select(trstprl) %>%
  mutate(year = 2020)

ess22 <- read.csv("../../ess/ESS11/ESS11.csv") %>% 
  filter(cntry == "DE") %>%
  dplyr::select(trstprl) %>%
  mutate(year = 2023)

# Combine all waves into a single dataframe
combined_ess <- bind_rows(ess02, ess04, ess06, ess08, ess10, ess12, ess14, ess16, ess18, ess20, ess22)
rm(ess02, ess04, ess06, ess08, ess10, ess12, ess14, ess16, ess18, ess20, ess22)


# table(combined_ess$trstprl, exclude = NULL) # Check distribution

combined_ess <- combined_ess %>% 
  mutate(trust_parliament = case_when(trstprl==0 ~ "No trust",
                                      trstprl>=1 & trstprl<=5 ~ "Low trust",
                                      trstprl>=6 & trstprl<=10 ~ "High trust",
                                      TRUE ~ NA))

ess.trust <- combined_ess %>% 
  group_by(year) %>% 
  summarise(`No trust` = sum(trust_parliament=="No trust", na.rm = TRUE),
            `Low trust` = sum(trust_parliament=="Low trust", na.rm = TRUE),
            `High trust` = sum(trust_parliament=="High trust", na.rm = TRUE),
            N = n()) %>% 
  mutate(across(c(`No trust`, `Low trust`, `High trust`),  ~ .x/N*100)) %>% 
  dplyr::select(-N) %>% 
    pivot_longer(!c(year), names_to = "Trust level", values_to = "Share") 

ggplot(data=ess.trust,aes(x=year, y=Share, linetype=`Trust level`)) + 
  geom_line() +
  theme(legend.text = element_text(size = 12)) + 
  theme_bw()  + xlab("Year") +
    scale_y_continuous(breaks = round(seq(-10, 80, by = 5), 1)) + 
  ylab("Share (%) per trust level") +
  ggtitle("Trust levels in German Federal parliament, Bundestag (ESS)") +
  ylim(0,70)

```


# Session info

```{r}
session_info()
```

